package com.yuven.appframework.widget

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

class HotKeyEditTextView : AppCompatEditText {

    private var index = 0
    private var listHotKeys = mutableListOf<String>()
    private var subscription: Disposable? = null
    private var timeInterval = 4L

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    fun setTimeInterval(period: Long) {
        this.timeInterval = period
    }

    @JvmOverloads
    fun setHotKeyList(keys: List<String>, defaultIndex: Int = 0) {
        listHotKeys.clear()
        listHotKeys.addAll(keys)
        index = defaultIndex
    }

    fun startToNext() {
        if (listHotKeys.isEmpty()) {
            return
        }
        if (listHotKeys.size == 1) {
            this.hint = listHotKeys[index]
            return
        }
        stop()
        subscription = Observable.interval(timeInterval, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe {
                this.hint = listHotKeys[index]
            }
            .subscribe {
                if (index == listHotKeys.size - 1) {
                    index = 0
                } else {
                    index++
                }
                this.hint = listHotKeys[index]
            }
    }

    fun stop() {
        subscription?.let {
            if (!it.isDisposed) {
                it.dispose()
            }
        }
    }

    fun getIndex(): Int {
        return listHotKeys.indexOf(hint.toString().trim())
    }

    fun getHotKeyList(): List<String> {
        return listHotKeys
    }
}